package bdz.projects.cbt.ui
{
	import bdz.common.events.DispatchChannel;
	import bdz.common.events.GenericEvent;
	import bdz.common.model.AppEnvironment;
	import bdz.projects.cbt.CBTGame;
	import bdz.projects.cbt.core.CBTPlayer;
	import bdz.projects.cbt.data.CBTData;
	import bdz.projects.cbt.events.CBTGameEvent;
	import bdz.projects.cbt.events.CBTUIEvent;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.utils.setTimeout;
	
	import gs.*;
	import gs.easing.*;
	
	public class CBTPanelLoader extends MovieClip
	{
		private var _channel:DispatchChannel = DispatchChannel.getChannel();
		private var _background:MovieClip;
		private var _easing:Function = Strong.easeInOut;
		private var _currentPanel:MovieClip;
		private var _game:CBTGame;
		private var _productList:CBTProductList;
		private var _inventoryList:CBTInventoryList;
		public function CBTPanelLoader(){
			super();
			visible = false;
			addEventListener(Event.ADDED_TO_STAGE, initializeComponent);
		}
		private function initializeComponent(evt:Event):void{
			
			_background = this["bg"];
			_background.mouseEnabled = false;
			_background.alpha = 0;
			
			_channel.addEventListener(CBTUIEvent.HOW_TO_PLAY, showHowToPlay);
			_channel.addEventListener(CBTUIEvent.SHOW_BUY_INTERFACE, showBuyInterface);
			_channel.addEventListener(CBTUIEvent.SHOW_MORTGAGE_INTERFACE, showMortgageInterface);
			_channel.addEventListener(CBTUIEvent.SHOW_PAYPAL_INTERFACE, showPayPalInterface);
			_channel.addEventListener(CBTUIEvent.SHOW_SELL_INTERFACE, showSellInterface);
			_channel.addEventListener(CBTUIEvent.SHOW_TRAVEL_INTERFACE, showTravelInterface);
			_channel.addEventListener(CBTUIEvent.TOP_SCORES, showTopScoresInterface);
			_channel.addEventListener(CBTUIEvent.SHOW_WAREHOUSE_UPGRADE, showWarehouseInterface);
			_channel.addEventListener(CBTUIEvent.QUIT_GAME, showQuitGamePanel);
			parent["navshortcut"].addEventListener(CBTUIEvent.PANEL_CLOSE, onNavShortCutClick);
			
		}
		private function onNavShortCutClick(evt:CBTUIEvent):void{
			resolveChanges(evt.data);
		}
		private function resolveChanges(obj:Object):void{
			
			if(obj.type == "topscore" && _game.daysLeft == 0 && _game.finished){
				_channel.dispatchEvent(new CBTGameEvent(CBTGameEvent.GAME_RESET, null));
			}
			try{
				removeChild(_currentPanel);
			}catch(e:Error){}
			
			switch(obj.type){
				case "viewtopscores":
					showTopScoresInterface();
				break;
				case "warehouseUpgrade":
					if(!obj.cancelled){
						if(obj.action == "yes"){
							_game.warehouseUpgrade(obj.amount, obj.mortgage);
						}
					}
				break;
				case "topscore":
					if(parent.contains(parent["_startForm"])){
						parent.setChildIndex(this, parent.numChildren-2);
					}else{
						parent.setChildIndex(this, parent.numChildren-1);
					}
				break;
				case "stolenMoney":
					_game.moneyStolen(obj.amount);
				break;
				case "locationChange":
					if(!obj.cancelled){
						_game.changeLocation(obj.location);
					}
				break;
				case "itemBought":
					if(obj.cancelled){
						break;
					}else{
						if(obj.paymentMode == "cash"){
							_game.player.cash.removeAmount(obj.totalCost);
						}else{
							_game.player.paypal.removeAmount(obj.totalCost);
						}
						_game.itemBought(obj.product, obj.quantity);
					}
				break;
				case "itemSold":
					if(obj.cancelled){
						break;
					}else{
						_game.itemSold(obj.totalSale, obj.quantity, obj.depositto == "cash", obj.alias);
						
					}
				break;
				case "paypalTransact":
					if(obj.cancelled){
						break;
					}else{
						if(obj.transact == "deposit"){
							_game.player.cash.value -= obj.amount;
							_game.player.paypal.value += obj.amount;
						}else{
							_game.player.cash.value += obj.amount;
							_game.player.paypal.value -= obj.amount;
						}
					}
					_game.paypalTransact();
				break;
				case "mortgageTransact":
					if(obj.cancelled){
						break;
					}else{
						if(obj.transact == "cash"){
							_game.player.cash.value -= obj.amount;
						}else{
							_game.player.paypal.value -= obj.amount;
						}
						_game.player.mortgage.removeAmount(obj.amount);
						_game.mortgageTransact();
						if(_game.player.mortgage.value > 0 && _game.player.totalWorth == 0){
							_game.checkEndGame();
						}
					}
				break;
			}
		}
		private function onPanelClose(evt:CBTUIEvent):void{
			//resolveChanges(evt.data);
			
			TweenMax.to(_currentPanel, .4, {alpha:0, scaleX:1.2, scaleY:1.2, ease:Strong.easeInOut, onComplete:resolveChanges, onCompleteParams:[evt.data]});
			//TweenMax.to(_currentPanel, .3, {alpha:0, scaleX:1.2, scaleY:1.2, ease:Strong.easeInOut, onComplete:removeChild, onCompleteParams:[_currentPanel]});
			TweenMax.to(_background, .3, {delay:.3, alpha:0, ease:Strong.easeInOut, onComplete:function(){visible=false;}});
			
		}
		private function showPanel(ui:MovieClip, addtoparent:Boolean = false):void{
			
			
			
			
			TweenMax.killTweensOf(_background);
			TweenMax.killTweensOf(_currentPanel);
			try{
				removeChild(_currentPanel);
			}catch(e:Error){}
			
			_background.mouseEnabled = true;
			visible = true;
			TweenMax.to(_background, .7, {alpha:1, ease:_easing});
			ui.addEventListener(CBTUIEvent.PANEL_CLOSE, onPanelClose);
			ui.alpha = 0;
			ui.x = Math.ceil(width/2);
			ui.y = Math.ceil(height/2);
			
			if(addtoparent){
				parent.addChild(ui);
			}else{
				addChild(ui);
			}
			_currentPanel = ui;
			
			TweenMax.to(ui, .3, {delay:.5, alpha:1, ease:Strong.easeInOut, onComplete:finalizePanel});
		}
		private function finalizePanel():void{
			
		}
		private function randomName():String{
			var r:String = "";
			for (var i:Number=0;i<Math.floor(Math.random()*5)+8;i++){
				r += String.fromCharCode(Math.floor(Math.random()*26)+62).toLowerCase();
			}
			return r;
		}
		private function onUserInserted(evt:GenericEvent):void{
			trace(evt.data);
		}
		private function testNewPlayer(cnt:Number):void{
			
			if(cnt < 1){
				
				var cdata:CBTData = CBTData.getInstance();
				cdata.addEventListener("userInserted", onUserInserted);
				var p:CBTPlayer = new CBTPlayer();
				var days:Array = [30, 60, 90];
				p.playerName = "tester boy";
				p.cash.addAmount(Math.floor(Math.random()*5000));
				p.addFeedback(Math.floor(Math.random()*1000));
				p.paypal.addAmount(Math.floor(Math.random()*5000));
				p.email = randomName();
				p.realName = randomName();
				p.maxDays = 30;
				p.cash.addAmount(3120432908490238490238);
				
				cdata.insertNewUser(p);
				setTimeout(testNewPlayer, 800, cnt+1);
			}
		}
		private function showTopScoresInterface(evt:CBTUIEvent = null):void{
			
			
			
			//testNewPlayer(0);
			//return;
			parent.setChildIndex(this, parent.numChildren-1);
			var topScoreInterface:MovieClip = new TopScoresPanel();
			showPanel(topScoreInterface);
			
			
			
		}
		private function showMortgageInterface(evt:CBTUIEvent):void{
			var mortgageInterface:MovieClip = new MortgagePanel();
			var gdata:Object = _game.gameData;
			gdata.inventoryReference = _inventoryList.dataProvider;
			gdata.productReference = _productList.dataProvider;
			
			mortgageInterface.info = gdata;
			showPanel(mortgageInterface);
		}
		private function showPayPalInterface(evt:CBTUIEvent):void{
			var paypalInteface:MovieClip = new PayPalPanel();
			var gdata:Object = _game.gameData;
			gdata.inventoryReference = _inventoryList.dataProvider;
			gdata.productReference = _productList.dataProvider;
			
			paypalInteface.info = gdata;
			showPanel(paypalInteface);
		}
		
		private function showTravelInterface(evt:CBTUIEvent):void{
			var travelInterface:MovieClip = new TravelPanel();
			travelInterface.currentloc = _game.currentLocation;
			showPanel(travelInterface);
			
		}
		private function showSellInterface(evt:CBTUIEvent):void{
			var sellInterface:MovieClip = new SellPanel();
			var gdata:Object = _game.gameData;
			gdata.inventoryReference = _inventoryList.dataProvider;
			gdata.productReference = _productList.dataProvider;
			
			sellInterface.info = gdata;
			showPanel(sellInterface);
		}
		private function showWarehouseInterface(evt:CBTUIEvent):void{
			var warehouseInterface:MovieClip = new WarehousePanel();
			var gdata:Object = _game.gameData;
			warehouseInterface.info = gdata;
			showPanel(warehouseInterface);
		}
		private function showQuitGamePanel(evt:CBTUIEvent):void{
			var quitGameInterface:MovieClip = new QuitGamePanel();
			var gdata:Object = _game.gameData;
			quitGameInterface.info = gdata;
			showPanel(quitGameInterface);
		}
		private function showBuyInterface(evt:CBTUIEvent):void{
			var buyInterface:MovieClip = new BuyPanel();
			var gdata:Object = _game.gameData;
			gdata.inventoryReference = _inventoryList.dataProvider;
			gdata.productReference = _productList.dataProvider;
			buyInterface.info = gdata;
			
			showPanel(buyInterface);
		}
		private function showMoneyStolenInterface(evt:CBTGameEvent):void{
			
			var stealInterface:MovieClip = new StolenPanel();
			var gdata:Object = _game.gameData;
			gdata.stealRate = AppEnvironment.getEnv().getSetting("stealRate");
			stealInterface.info = gdata;
			showPanel(stealInterface);
		}
		private function onGameFinalized(evt:CBTGameEvent):void{
			var gameend:MovieClip = new GameOverPanel();
			_game.finished = true;
			gameend.info = evt.data;
			showPanel(gameend);
		}
		private function showHowToPlay(evt:CBTUIEvent):void{
			parent.setChildIndex(this, parent.numChildren-1);
			var howtoplay:MovieClip = new HowToPlayPanel();
			howtoplay.info = evt.data;
			showPanel(howtoplay);
		}
		public function set productList(pl:CBTProductList):void{
			_productList = pl;
		}
		public function set inventoryList(il:CBTInventoryList):void{
			_inventoryList = il;
		}
		public function set game(g:CBTGame):void{
			_game = g;
			_game.addEventListener(CBTGameEvent.MONEY_STOLEN, showMoneyStolenInterface);
			_game.addEventListener(CBTGameEvent.GAME_FINALIZED, onGameFinalized);
		}
		public function get game():CBTGame{
			return _game;
		}
		
	}
}